synchronized与 lock

区别
1)Lock不是Java语言内置的,synchronized是Java语言的关键字。Lock是一个接口,通过这个接口的实现类可以实现同步访问;
2)采用synchronized不需要手动释放锁,当synchronized方法或者synchronized代码块执行完之后,系统会自动让线程释放对锁的占用;而Lock则必须要用户去手动释放锁,如果没有主动释放锁,就有可能导致出现死锁现象。

使用synchronized同步交替打印-Runnable

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package ThreadTest;

/**
* @author: Hongyuan Bai
* @create: 2018-12-27 14:13:39
* @description: 实现ruannable接口方式创建多线程
*/
public class Thread1 implements Runnable{

int sum = 200;
@Override
public void run() {

synchronized (this) {
while (sum > 0) {
try {
this.notify();

System.out.println(sum-- + Thread.currentThread().getName());
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}

}
}
}
}

使用synchronized同步交替打印-Thread类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package ThreadTest;

/**
* @author: Hongyuan Bai
* @create: 2018-12-28 09:50:44
* @description: 继承Thread类方式创建多线程
*/
public class Thread2 extends Thread{

static int sum = 200;
Object obj;

public Thread2() {
}

public Thread2(Object obj) {
this.obj = obj;
}

@Override
public void run() {
synchronized (obj) {

while (sum > 0) {
try {
obj.notify();

System.out.println(sum-- + Thread.currentThread().getName());

obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}

Lock实现同步

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package ThreadTest;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
* @author: Hongyuan Bai
* @create: 2018-12-28 10:54:42
* @description: Lock实现同步
*/
public class Thread3 implements Runnable{

int sum = 200;

Lock lock = new ReentrantLock();

@Override
public void run() {

lock.lock();
try {
while (sum > 0) {
System.out.println(sum-- + Thread.currentThread().getName());
}
} finally {
lock.unlock();
}
}
}